import { Component, Input } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';


export interface TreeNode {
  id?: any;
  label?: string;
  children?: TreeNode[];
  [key: string]: any;
}

@Component({
  selector: 'app-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.scss']
})
export class TreeComponent {
  @Input() nodes: TreeNode[];
  @Input() displayedColumns: string[] = ['label'];
  @Input() childFieldNames: string[] = ['children'];
  @Input() displayFieldNames: string[] = ['label'];

  drop(event: CdkDragDrop<TreeNode[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      this.moveNode(event);
    }
  }

  private moveNode(event: CdkDragDrop<TreeNode[]>) {
    const previousContainerData = event.previousContainer.data as TreeNode[];
    const containerData = event.container.data as TreeNode[];

    const nodeToMove = previousContainerData[event.previousIndex];

    // 将节点从原位置移除
    previousContainerData.splice(event.previousIndex, 1);

    // 插入节点到新位置
    containerData.splice(event.currentIndex, 0, nodeToMove);
  }

  toggleNode(node: TreeNode) {
    node.expanded = !node.expanded;
  }

  deleteNode(nodes: TreeNode[], index: number) {
    nodes.splice(index, 1);
  }

  getChildren(node: TreeNode, level: number): TreeNode[] {
    const field = this.childFieldNames[level] || this.childFieldNames[this.childFieldNames.length - 1];
    return node[field] || [];
  }

  getDisplayField(node: TreeNode, level: number, field: string): any {
    const displayField = this.displayFieldNames[level] || this.displayFieldNames[this.displayFieldNames.length - 1];
    return node[displayField];
  }
}
